<?php
class NhdActivityRecordsController extends AppController {

	var $name = 'NhdActivityRecords';
	
	public function beforeFilter() {
            parent::beforeFilter();
            //$this->Auth->allow('index');
        }
	
	function index()
	{
		$city_id = $this->Session->read("c_city_id");
		$year = $this->Session->read("c_year");
		$quarter = $this->Session->read("c_quarter");
		
		$this->layout = 'home';
		
		
		$users = $this->NhdActivityRecord->User->find('list');		
		$nhdActivities = $this->NhdActivityRecord->NhdActivity->find('all');
		foreach($nhdActivities as $k => $item)
		{			
			$record = $this->NhdActivityRecord->find("first", array(
											'conditions' => array(
												'NhdActivityRecord.city_id' => $city_id,
												'NhdActivityRecord.nhd_activity_id' => $item["NhdActivity"]["id"],
												'NhdActivityRecord.year' => $year,
												'NhdActivityRecord.quarter' => $quarter
											)
										));
			
			//format number
			if(isset($record["NhdActivityRecord"]["school_num"])) {
				$record["NhdActivityRecord"]["school_num"] = $record["NhdActivityRecord"]["school_num"] != '' ? number_format($record["NhdActivityRecord"]["school_num"],0,".", ","): '';
				$record["NhdActivityRecord"]["school_rate"] = $record["NhdActivityRecord"]["school_rate"] != '' ? number_format($record["NhdActivityRecord"]["school_rate"],2,".", ","): '';
				$record["NhdActivityRecord"]["student_num"] = $record["NhdActivityRecord"]["student_num"] != '' ? number_format($record["NhdActivityRecord"]["student_num"],0,".", ","): '';
				$record["NhdActivityRecord"]["student_rate"] = $record["NhdActivityRecord"]["student_rate"] != '' ? number_format($record["NhdActivityRecord"]["student_rate"],2,".", ","): '';
			}
			
			if(!empty($record["NhdActivityRecord"]["id"]))
			{
				$nhdActivities[$k]["NhdActivityRecord"] = $record["NhdActivityRecord"];
			}
			else
			{
				$nhdActivities[$k]["NhdActivityRecord"] = array("NhdActivityRecord"=>array('school_num'=>'','school_rate'=>'','student_num'=>'','student_rate'=>'',));
			}
		}
		
		//echo $bs_rhm;
		$popDocs = $this->getDoctorPopulation($city_id, $year, $quarter);
		$doctor_student = $popDocs['doctors_nhd'] ? round($popDocs['students']/$popDocs['doctors_nhd'],0) :0;
		$nondoctor_student = $popDocs['nondoctors_nhd'] ? round($popDocs['students']/$popDocs['nondoctors_nhd'],0) :0;
		
		$this->set(compact('nhdActivities', 'doctor_student', 'nondoctor_student'));
	}
	
	function getDoctorPopulation($city_id, $year, $quarter)
	{
		Controller::loadModel('HumanResource');
		Controller::loadModel('NhdHumanResource');
		Controller::loadModel('CityDetail');
		Controller::loadModel('NhdActivityRecord');
		
		$cities = $this->HumanResource->City->find('all', array(
								'fields'=>array('City.id'),
								'contain'=>false,
								'conditions'=>array(									
									'City.id'=>$city_id
								)
							));
		//var_dump($cities);
		$city_array = $city_id;
		
		//var_dump($city_array);
		
		$employee_array = array(1,2);
		$doctors = $this->HumanResource->find('all', array(
						      'fields'=>array('SUM(HumanResource.value) AS doctors'),
						      'conditions'=>array(
								'HumanResource.employee_id'=>$employee_array,
								'HumanResource.city_id'=>$city_array,
								'HumanResource.year'=>$year,
								'HumanResource.quarter'=>$quarter
						      )
						));
		
		
		//dan so tinh khu vuc
		$population = $this->CityDetail->find('all', array(
								'fields'=>array('SUM(CityDetail.population) AS population'),
								'conditions'=>array(									  
									  'CityDetail.city_id'=>$city_array,
									  'CityDetail.year'=>$year
								)
							));

		//so hoc sinh
		$nd1_a = array(1,2);
		$students = $this->NhdActivityRecord->find('all', array(
								'fields'=>array('SUM(NhdActivityRecord.student_num) AS student_num'),
								'conditions'=>array(									  
									  'NhdActivityRecord.city_id'=>$city_array,
									  'NhdActivityRecord.nhd_activity_id'=>$nd1_a,
									  'NhdActivityRecord.year'=>$year,
									  'NhdActivityRecord.quarter'=>$quarter
								)
							));
		
		//BS RHM NHD
		$employee_nhd_array = array(10,11);
		$doctors_nhd = $this->NhdHumanResource->find('all', array(
						      'fields'=>array('SUM(NhdHumanResource.value) AS doctors'),
						      'conditions'=>array(
								'NhdHumanResource.employee_id'=>$employee_nhd_array,
								'NhdHumanResource.city_id'=>$city_array,
								'NhdHumanResource.year'=>$year,
								'NhdHumanResource.quarter'=>$quarter
						      )
						));
		//BS RHM NHD
		$employee_nhd_array = array(12,13,14,15);
		$nondoctors_nhd = $this->NhdHumanResource->find('all', array(
						      'fields'=>array('SUM(NhdHumanResource.value) AS doctors'),
						      'conditions'=>array(
								'NhdHumanResource.employee_id'=>$employee_nhd_array,
								'NhdHumanResource.city_id'=>$city_array,
								'NhdHumanResource.year'=>$year,
								'NhdHumanResource.quarter'=>$quarter
						      )
						));
		
		return array('population'=>$population[0][0]["population"], 'doctors'=>$doctors[0][0]["doctors"], 'students'=>$students[0][0]["student_num"], 'doctors_nhd'=>$doctors_nhd[0][0]["doctors"], 'nondoctors_nhd'=>$nondoctors_nhd[0][0]["doctors"]);
	}

	function manager_index() {
		$this->NhdActivityRecord->recursive = 0;
		
		//get cities list
		Controller::loadModel('City');
		$user = $this->Auth->user();
		$cities = $this->City->citiesByUser($user["User"]["id"]);
		$c_year = $this->Session->read("c_year");
		$c_quarter = $this->Session->read("c_quarter");
		
		$conditions = array();
		//filter city id
		$city_id = !empty($this->params['form']['filter_city_id']) && $this->params['form']['filter_city_id'] != "" ? $this->params['form']['filter_city_id'] : $cities[0]["City"]["id"];
		if($city_id)
		{
			$conditions["NhdActivityRecord.city_id"] = $city_id;
		}		
		
		//filter year
		$year = !empty($this->params['form']['filter_year']) && $this->params['form']['filter_year'] != "" ? $this->params['form']['filter_year'] : $c_year;
		if($year)
		{
			$conditions["NhdActivityRecord.year"] = $year;
		}
		
		
		//var_dump($this->params);
		if(count($conditions))
		{
			$this->paginate = array(
				'conditions' => $conditions				
			);
		}
		
		
		
		$this->set('nhdActivityRecords', $this->paginate());
		$this->set('city_id', $city_id);
		$this->set('year', $year);
		$this->set('cities', $cities);
	}

	function manager_view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid nhd activity record', true));
			$this->redirect(array('action' => 'index'));
		}
		$this->set('nhdActivityRecord', $this->NhdActivityRecord->read(null, $id));
	}
	
	function admin_add() {
		
		if(!$this->Session->read("isActive"))
		{
			$this->redirect(array('controller'=>'users' , 'action' => 'offline', 'manager'=>false));
		}
		//get user
		$c_year = $this->Session->read("c_year");
		$c_quarter = $this->Session->read("c_quarter");
		$user = $this->Auth->user();
		$user = $this->NhdActivityRecord->User->find("first", array(
									'conditions'=>array('User.id'=>$user["User"]["id"])									
								));
		
		//find city_id
		$cities = $user["City"];
		if(!empty($this->params['form']['filter_city_id']))
		{
			foreach($cities as $c)
			{
				if($c["id"] == $this->params['form']['filter_city_id'])
				{
					$city = $c;
					break;
				}
			}
		}
		else if(!empty($this->data["NhdActivityRecord"]["city_id"]))
		{
			$city = $this->NhdActivityRecord->City->find("first", array(
									'conditions'=>array('City.id'=>$this->data["NhdActivityRecord"]["city_id"])									
								));
			$city = $city["City"];
		}
		else
		{
			$city = $user["City"][0];
		}
		
		$year = !empty($this->params['form']['filter_year']) ? $this->params['form']['filter_year'] : $c_year;
		$quarter = !empty($this->params['form']['filter_quarter']) ? $this->params['form']['filter_quarter'] : $c_quarter;
		//$year = date('Y');
		//$quarter = date('m')%3 + 1;
		
		if (!empty($this->data)) {
			//var_dump($this->data);
			foreach($this->data["NhdActivityRecord"]["records"] as $aid => $item)
			{
				$record["NhdActivityRecord"] = $item;
				$record["NhdActivityRecord"]["user_id"] = $user["User"]["id"];
				$record["NhdActivityRecord"]["city_id"] = $this->data["NhdActivityRecord"]["city_id"];
				$record["NhdActivityRecord"]["year"] = $this->data["NhdActivityRecord"]["year"];
				$record["NhdActivityRecord"]["quarter"] = $this->data["NhdActivityRecord"]["quarter"];
				$record["NhdActivityRecord"]["nhd_activity_id"] = $aid;		
				
				$record["NhdActivityRecord"]["school_num"] = str_replace(",", "", $record["NhdActivityRecord"]["school_num"]);
				$record["NhdActivityRecord"]["school_rate"] = str_replace(",", "", $record["NhdActivityRecord"]["school_rate"]);
				$record["NhdActivityRecord"]["student_num"] = str_replace(",", "", $record["NhdActivityRecord"]["student_num"]);
				$record["NhdActivityRecord"]["student_rate"] = str_replace(",", "", $record["NhdActivityRecord"]["student_rate"]);
				
				//set year
				$year = $this->data["NhdActivityRecord"]["year"];
				//set year
				$quarter = $this->data["NhdActivityRecord"]["quarter"];
				
				//var_dump($record);
				
				//check if record exsits
				$exsit = $this->NhdActivityRecord->find("first", array(
											'conditions' => array(
												'NhdActivityRecord.city_id' => $record["NhdActivityRecord"]["city_id"],
												'NhdActivityRecord.nhd_activity_id' => $record["NhdActivityRecord"]["nhd_activity_id"],
												'NhdActivityRecord.year' => $record["NhdActivityRecord"]["year"],
												'NhdActivityRecord.quarter' => $record["NhdActivityRecord"]["quarter"]
											)
										));
				
				if(empty($exsit["NhdActivityRecord"]["id"]))
				{
					$this->NhdActivityRecord->create();
					if ($this->NhdActivityRecord->save($record)) {
						$this->Session->setFlash(__('Thông tin đã được lưu', true));
						//$this->redirect(array('action' => 'index'));
					} else {
						//$this->Session->setFlash(__('The nhd activity record could not be saved. Please, try again.', true));
					}
				}
				else
				{
					$record["NhdActivityRecord"]["id"] = $exsit["NhdActivityRecord"]["id"];
					//$this->NhdActivityRecord->create();
					if ($this->NhdActivityRecord->save($record)) {
						$this->Session->setFlash(__('Thông tin đã được lưu', true));
						//$this->redirect(array('action' => 'index'));
					} else {
						//$this->Session->setFlash(__('The nhd activity record could not be saved. Please, try again.', true));
					}
				}
			}
			
			//$this->NhdActivityRecord->create();
			//if ($this->NhdActivityRecord->save($this->data)) {
			//	$this->Session->setFlash(__('The nhd activity record has been saved', true));
			//	$this->redirect(array('action' => 'index'));
			//} else {
			//	$this->Session->setFlash(__('The nhd activity record could not be saved. Please, try again.', true));
			//}
		}
		$users = $this->NhdActivityRecord->User->find('list');		
		$nhdActivities = $this->NhdActivityRecord->NhdActivity->find('all');
		foreach($nhdActivities as $k => $item)
		{			
			$record = $this->NhdActivityRecord->find("first", array(
											'conditions' => array(
												'NhdActivityRecord.city_id' => $city["id"],
												'NhdActivityRecord.nhd_activity_id' => $item["NhdActivity"]["id"],
												'NhdActivityRecord.year' => $year,
												'NhdActivityRecord.quarter' => $quarter
											)
										));
			
			//format number
			if(isset($record["NhdActivityRecord"]["id"]))
			{
				$record["NhdActivityRecord"]["school_num"] = $record["NhdActivityRecord"]["school_num"] != '' ? number_format($record["NhdActivityRecord"]["school_num"],0,".", ","): '';
				$record["NhdActivityRecord"]["school_rate"] = $record["NhdActivityRecord"]["school_rate"] != '' ? number_format($record["NhdActivityRecord"]["school_rate"],2,".", ","): '';
				$record["NhdActivityRecord"]["student_num"] = $record["NhdActivityRecord"]["student_num"] != '' ? number_format($record["NhdActivityRecord"]["student_num"],0,".", ","): '';
				$record["NhdActivityRecord"]["student_rate"] = $record["NhdActivityRecord"]["student_rate"] != '' ? number_format($record["NhdActivityRecord"]["student_rate"],2,".", ","): '';
			}
			
			
			if(!empty($record["NhdActivityRecord"]["id"]))
			{
				$nhdActivities[$k]["NhdActivityRecord"] = $record["NhdActivityRecord"];
			}
			else
			{
				$nhdActivities[$k]["NhdActivityRecord"] = array('school_num'=>'','school_rate'=>'','student_num'=>'','student_rate'=>'');
			}
		}
		//$this->data["HumanResource"]["unit_id"] = !empty($this->data["HumanResource"]["unit_id"])?$this->data["HumanResource"]["unit_id"]:3;
		$units = $this->NhdActivityRecord->Unit->find('list');
		$this->set(compact('users', 'cities', 'nhdActivities', 'units', 'city', 'year', 'quarter'));
	}

	function manager_add() {
		
		if(!$this->Session->read("isActive"))
		{
			$this->redirect(array('controller'=>'users' , 'action' => 'offline', 'manager'=>false));
		}
		//get user
		$c_year = $this->Session->read("c_year");
		$c_quarter = $this->Session->read("c_quarter");
		$user = $this->Auth->user();
		$user = $this->NhdActivityRecord->User->find("first", array(
									'conditions'=>array('User.id'=>$user["User"]["id"])									
								));
		
		//find city_id
		$cities = $user["City"];
		if(!empty($this->params['form']['filter_city_id']))
		{
			foreach($cities as $c)
			{
				if($c["id"] == $this->params['form']['filter_city_id'])
				{
					$city = $c;
					break;
				}
			}
		}
		else if(!empty($this->data["NhdActivityRecord"]["city_id"]))
		{
			$city = $this->NhdActivityRecord->City->find("first", array(
									'conditions'=>array('City.id'=>$this->data["NhdActivityRecord"]["city_id"])									
								));
			$city = $city["City"];
		}
		else
		{
			$city = $user["City"][0];
		}
		
		//$year = !empty($this->params['form']['filter_year']) ? $this->params['form']['filter_year'] : $c_year;
		//$quarter = !empty($this->params['form']['filter_quarter']) ? $this->params['form']['filter_quarter'] : $c_quarter;
		$year = date('Y');
		$quarter = round(date('m')/3,0);
		
		if (!empty($this->data)) {
			//var_dump($this->data);
			foreach($this->data["NhdActivityRecord"]["records"] as $aid => $item)
			{
				$record["NhdActivityRecord"] = $item;
				$record["NhdActivityRecord"]["user_id"] = $user["User"]["id"];
				$record["NhdActivityRecord"]["city_id"] = $this->data["NhdActivityRecord"]["city_id"];
				$record["NhdActivityRecord"]["year"] = $this->data["NhdActivityRecord"]["year"];
				$record["NhdActivityRecord"]["quarter"] = $this->data["NhdActivityRecord"]["quarter"];
				$record["NhdActivityRecord"]["nhd_activity_id"] = $aid;		
				
				$record["NhdActivityRecord"]["school_num"] = str_replace(",", "", $record["NhdActivityRecord"]["school_num"]);
				$record["NhdActivityRecord"]["school_rate"] = str_replace(",", "", $record["NhdActivityRecord"]["school_rate"]);
				$record["NhdActivityRecord"]["student_num"] = str_replace(",", "", $record["NhdActivityRecord"]["student_num"]);
				$record["NhdActivityRecord"]["student_rate"] = str_replace(",", "", $record["NhdActivityRecord"]["student_rate"]);
				
				//set year
				$year = $this->data["NhdActivityRecord"]["year"];
				//set year
				$quarter = $this->data["NhdActivityRecord"]["quarter"];
				
				//var_dump($record);
				
				//check if record exsits
				$exsit = $this->NhdActivityRecord->find("first", array(
											'conditions' => array(
												'NhdActivityRecord.city_id' => $record["NhdActivityRecord"]["city_id"],
												'NhdActivityRecord.nhd_activity_id' => $record["NhdActivityRecord"]["nhd_activity_id"],
												'NhdActivityRecord.year' => $record["NhdActivityRecord"]["year"],
												'NhdActivityRecord.quarter' => $record["NhdActivityRecord"]["quarter"]
											)
										));
				
				if(empty($exsit["NhdActivityRecord"]["id"]))
				{
					$this->NhdActivityRecord->create();
					if ($this->NhdActivityRecord->save($record)) {
						$this->Session->setFlash(__('Thông tin đã được lưu', true));
						//$this->redirect(array('action' => 'index'));
					} else {
						//$this->Session->setFlash(__('The nhd activity record could not be saved. Please, try again.', true));
					}
				}
				else
				{
					$record["NhdActivityRecord"]["id"] = $exsit["NhdActivityRecord"]["id"];
					//$this->NhdActivityRecord->create();
					if ($this->NhdActivityRecord->save($record)) {
						$this->Session->setFlash(__('Thông tin đã được lưu', true));
						//$this->redirect(array('action' => 'index'));
					} else {
						//$this->Session->setFlash(__('The nhd activity record could not be saved. Please, try again.', true));
					}
				}
			}
			
			//$this->NhdActivityRecord->create();
			//if ($this->NhdActivityRecord->save($this->data)) {
			//	$this->Session->setFlash(__('The nhd activity record has been saved', true));
			//	$this->redirect(array('action' => 'index'));
			//} else {
			//	$this->Session->setFlash(__('The nhd activity record could not be saved. Please, try again.', true));
			//}
		}
		$users = $this->NhdActivityRecord->User->find('list');		
		$nhdActivities = $this->NhdActivityRecord->NhdActivity->find('all');
		foreach($nhdActivities as $k => $item)
		{			
			$record = $this->NhdActivityRecord->find("first", array(
											'conditions' => array(
												'NhdActivityRecord.city_id' => $city["id"],
												'NhdActivityRecord.nhd_activity_id' => $item["NhdActivity"]["id"],
												'NhdActivityRecord.year' => $year,
												'NhdActivityRecord.quarter' => $quarter
											)
										));
			
			//format number
			if(isset($record["NhdActivityRecord"]["id"]))
			{
				$record["NhdActivityRecord"]["school_num"] = $record["NhdActivityRecord"]["school_num"] != '' ? number_format($record["NhdActivityRecord"]["school_num"],0,".", ","): '';
				$record["NhdActivityRecord"]["school_rate"] = $record["NhdActivityRecord"]["school_rate"] != '' ? number_format($record["NhdActivityRecord"]["school_rate"],2,".", ","): '';
				$record["NhdActivityRecord"]["student_num"] = $record["NhdActivityRecord"]["student_num"] != '' ? number_format($record["NhdActivityRecord"]["student_num"],0,".", ","): '';
				$record["NhdActivityRecord"]["student_rate"] = $record["NhdActivityRecord"]["student_rate"] != '' ? number_format($record["NhdActivityRecord"]["student_rate"],2,".", ","): '';
			}
			
			
			if(!empty($record["NhdActivityRecord"]["id"]))
			{
				$nhdActivities[$k]["NhdActivityRecord"] = $record["NhdActivityRecord"];
			}
			else
			{
				$nhdActivities[$k]["NhdActivityRecord"] = array('school_num'=>'','school_rate'=>'','student_num'=>'','student_rate'=>'');
			}
		}
		//$this->data["HumanResource"]["unit_id"] = !empty($this->data["HumanResource"]["unit_id"])?$this->data["HumanResource"]["unit_id"]:3;
		$units = $this->NhdActivityRecord->Unit->find('list');
		$this->set(compact('users', 'cities', 'nhdActivities', 'units', 'city', 'year', 'quarter'));
	}

	function manager_edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid nhd activity record', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
			if ($this->NhdActivityRecord->save($this->data)) {
				$this->Session->setFlash(__('The nhd activity record has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The nhd activity record could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->NhdActivityRecord->read(null, $id);
		}
		$users = $this->NhdActivityRecord->User->find('list');
		$cities = $this->NhdActivityRecord->City->find('list');
		$nhdActivities = $this->NhdActivityRecord->NhdActivity->find('list');
		$units = $this->NhdActivityRecord->Unit->find('list');
		$this->set(compact('users', 'cities', 'nhdActivities', 'units'));
	}

	function manager_delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for nhd activity record', true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->NhdActivityRecord->delete($id)) {
			$this->Session->setFlash(__('Nhd activity record deleted', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->Session->setFlash(__('Nhd activity record was not deleted', true));
		$this->redirect(array('action' => 'index'));
	}
}
